﻿using BlogsAPI.Images;
using BlogsAPI.OneBlog;
using BlogsAPI.Sites.FoursquareSharp;
using InstaSharp.Models.Responses;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RssToolkit.Xml;
using Twitterizer;

namespace BlogAPIUnitTest
{
    using RssToolkit.Rss;
    using System;
    using System.Text;
    using BlogsAPI.Abstract;
    using System.Net;
    using BlogsAPI;
    using System.IO;
    using BlogsAPI.Sites;
    using System.Diagnostics;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Класс для логирования сообщений в отладчик
    /// </summary>
    public static class Common
    {

        /// <summary>
        /// Запись в отладку
        /// </summary>
        /// <param name="sText">текст для записи</param>
        static public void Dp(string sText)
        {
            Debug.WriteLine(sText);
        }
    }

    /// <summary>
    /// Проверим, доступны ли сервисы и работают ли они как положено
    /// </summary>
    [TestClass]
    public class MainTests
    {
        //[Test(Description="Проверка создания объектов")]
        [TestMethod]
        public void ObjectsInit()
        {
#pragma warning disable 168
            Liveinternet liru = new Liveinternet();
            Livejournal lj = new Livejournal();
            BlogsMail mail = new BlogsMail();
            StandAlone alone = new StandAlone();
            YaRu ya = new YaRu();
            UserAccount user = new UserAccount("log", "pass");
            PostResult pr = new PostResult();
            BlogPost bp = new BlogPost();
            CommentPost cp = new CommentPost();
            Common.Dp("Init Test Finished!");
#pragma warning restore 168
        }

        //[Test(Description="Проверка соединения с интернетом")]
        [TestMethod]
        public void IsInetConnected()
        {
            const string sUrl = "http://google.com";
            Common.Dp("Retrying url: " + sUrl);
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(sUrl);
            
            //никуда не следуем
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
#pragma warning disable 168
            string result = new StreamReader(myHttpWebResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();
#pragma warning restore 168
            myHttpWebResponse.Close();
        }


        //[Test(Description="Перечисление всех типво классов")]
        [TestMethod]
        public void EnumerateClasses()
        {
            Type[] classes = BlogsAPI.Common.EnumerateClassesInNameSpace();
            Assert.AreNotEqual(null,classes);
            Common.Dp("Всего найдено "+classes.Length+" сервисов");
            foreach(Type oneclass in classes){
                Common.Dp("Наден класс : " + oneclass);
            }
            Assert.IsTrue(classes.Length > 0);
        }

        //[Test(Description = "Проверка регулярного выражения")]
        [TestMethod]
        public void rHttpText()
        {
            string sLink = "http://yandex.ru";
            Assert.IsTrue(String.Compare(sLink,BlogsAPI.Common.FixHttp(BlogsAPI.Common.DelHttp(sLink)))==0);
        }

        //[Test(Description="Проверка получений типа блога по ссылкам")]
        [TestMethod]
        public void ValidateCheck()
        {
            var bloglinks = new []{
                "https://www.facebook.com/people/%EC%84%9C%EC%98%88%EC%A7%80/100011056275300",
                "http://twitch.tv/dr_lizardov",
                "https://www.facebook.com/generationbrand/photos/a.523618047690732.1073741829.523606127691924/865853223467211/?type=1",
                "https://plus.google.com/+ОксанаГачева/posts/KgvHnmK7RSf",
                "http://instagr.am/h.elena.s",
                "http://my.mail.ru/community/yamuna/0A6FB6EFDBD0F909.html?thread=217BC18883B63ADC",
                "http://kobiak.livejournal.com/225901.html?thread=2031725#t2031725",
                "http://my.mail.ru/video/mail/tapo4kin333/_myvideo#video=/mail/tapo4kin333/_myvideo/2259",
                "http://m.livejournal.com/read/user/malyshi/44326365/comments/p1",
                "http://vk.com/wall189009486_400",
                "http://instagram.com/p/PXxOEfyHwE/",
                "http://www.facebook.com/Top30posts",
                "http://www.facebook.com/profile.php?id=100000869227964",
                "http://www.livejournal.com/misc/latestqotd.bml?qid=2750",
                "http://blog.sport-express.ru/community/futbol/post116841763/",
                "http://blog.sport-express.ru/users/dzich/post116835496/",
                "http://affinity4you.ru/post114896889/",
                "http://gallerynikole.com/post115040632/",
                "http://www.liveinternet.ru/users/topbot_flashr",
                "http://users.livejournal.com/_corso_/161709.html",
                "http://lleo.aha.ru/dnevnik/2009/07/24.html",
                "http://tema.livejournal.com",
                "http://www.livejournal.com/users/flashr",
                "http://community.livejournal.com/ru_sex",
                "http://www.livejournal.com/community/ru_sex",
                "http://flashr.ya.ru",
                "http://blogs.mail.ru/mail/topbot30",
                "http://www.liveinternet.ru/users/flashr/",
                "http://www.liveinternet.ru/community/778442",
                "http://ya.topbot.ru",
                "http://be-do-have.livejournal.com/friends/mutual+friends",
                "http://www.liveinternet.ru/ribbon.php?journalid=809153&action=friend",
                "http://my.mail.ru/community/abto_moto",
                //"http://www.livejournal.com/editjournal.bml?usejournal=prizolovy",
                "http://twitter.com/ru_medvedev",
                "http://twitter.com/#!/blog_medvedev",
                "http://someunknownsite.ru/?params=1",
                "http://www.youtube.com/channel/UCjvxgzf8yt1ycy1h53ces8g",
                "http://player.twitch.tv/?channel=volodyamedvedd#201601091337",
                "http://45.media.tumblr.com/3890459e967a3b5cbcae71ab1f8c9182/tumblr_nqv677sHuo1r4litgo1_500.gif"
            };
            
            foreach(string slink in bloglinks){
                String u;
                BlogType t;
                var v = BlogsAPI.Common.GetBlogServiceByLink(slink, out u, out t);
                Assert.AreNotEqual(v, null);
                Common.Dp("ValidateCheck for " + slink + " succeed with result: " + v + " " + u + " " + t + " micro:" + ((BlogServer) v).IsMicroblog);
            }
            
        }

        //[Test(Description="Определение RSS ссылки для блога")]
        [TestMethod]
        public void StandAloneRss()
        {
            StandAlone sa = new StandAlone();
            Assert.AreEqual(0,String.Compare("http://feeds.feedburner.com/Topbot",sa.GetRssLink("ya.topbot.ru",BlogType.Unknown),true));
        }

        //[Test(Description = "Определение RSS ссылки для блога")]
        [TestMethod]
        public void MediumRss()
        {
            var rss = BlogsAPI.Common.GetPostByRSS(
                "https://medium.com/russian/%D1%81%D0%B4%D0%B5%D0%BB%D0%B0%D0%B9%D1%82%D0%B5-%D0%BC%D0%BD%D0%B5-%D0%BF%D1%80%D0%BE%D0%B4%D0%B0%D0%B6%D0%B8-%D0%B0-%D1%8F-%D0%B2%D0%B0%D0%BC-%D0%B7%D0%B0%D0%BF%D0%BB%D0%B0%D1%87%D1%83-c0a753151db7");
            Assert.IsNotNull(rss);
        }

        //[Test(Description ="Наследственная целостность для стендалонов" )]
        [TestMethod]
        public void Inheritances()
        {
            Assert.AreEqual(typeof(Livejournal).BaseType, typeof(BlogServer));
            Assert.AreEqual(typeof(StandAlone).BaseType, typeof(BlogServer));
            Assert.AreEqual(typeof(Lleo).BaseType, typeof (StandAlone));
            Assert.AreEqual(typeof(Mamba).BaseType, typeof(StandAlone));
            Assert.AreEqual(typeof(Fishki).BaseType, typeof(StandAlone));
        }

        //[Test(Description = "Определение полного имени блога по имени и типу")]
        [TestMethod]
        public void GetBlogUri()
        {
            string userName = "tema";
            string blogServ = "Livejournal";

            Common.Dp("Формирование имени блога http://tema.livejournal.com");
            Assert.AreEqual(new Uri("http://tema.livejournal.com"),
                BlogsAPI.Common.GetBlogUri(blogServ, userName, BlogType.User));
        }

        //[Test(Description = "Rss loading test")]
        [TestMethod]
        public void LoadComplexRss()
        {
            RssDocument xDoc = RssDocument.Load(new Uri("http://promo.t30p.ru/syndication.axd"), false);
            Assert.AreNotEqual(xDoc, null);
            Assert.IsTrue(xDoc.Channel.Items.Count > 0);
        }

        //[Test(Description = "Rss Yahoo style test")]
        [TestMethod]
        public void LoadComplexRss2()
        {
            RssDocument xDoc = RssDocument.Load(new Uri("http://www.liveleak.com/rss?selection=all&safe_mode=off"), false);
            Assert.AreNotEqual(xDoc, null);
            Assert.IsTrue(xDoc.Channel.Items.Count > 0);
            Debug.WriteLine(xDoc.ToXml(DocumentType.Rss));
        }

        //[Test(Description = "Получение локации по ссылке")]
        [TestMethod]
        public async void GetLocation()
        {
            Foursquare sq = new Foursquare();
            //JObject temp = sq.GetLocation("http://4sq.com/vBvAs4");
            JObject temp = sq.GetLocation("http://4sq.com/14Xz31O");
            //http://4sq.com/14Xz31O
            Debug.WriteLine(temp);//http://4sq.com/vBvAs4

            InstaSharp.Endpoints.Media client = new InstaSharp.Endpoints.Media(Instagram.APIKey);
            var medias = await client.Search(temp["lat"].Value<double>(), temp["lng"].Value<double>());

            Debug.WriteLine(medias.Data);
            Assert.IsTrue(medias.Data.Count > 0);
        }

        //[Test(Description = "Получение последних фоток")]
        [TestMethod]
        public async void GetRecentInstagram()
        {
            InstaSharp.Endpoints.Users client = new InstaSharp.Endpoints.Users(Instagram.APIKey);
            var users = await client.Search("t30pru", 1);
            Assert.IsTrue(users != null && users.Data.Count == 1);
            var medias = await client.Recent(users.Data[0].Id);
            Assert.IsTrue(medias.Data.Count > 0);
        }

        //[Test(Description = "Получение поста по RSS for LJ")]
        [TestMethod]
        public void GetOnePostLJ()
        {
            var lj = new Livejournal();
            BlogsAPI.Common.GetPostByRSS("http://tipaa-etaa.livejournal.com/4031608.html");
            BlogPost bp = lj.GetOnePost("http://tipaa-etaa.livejournal.com/4031608.html");
            Assert.AreEqual(bp.Existance, true);
        }

        //[Test(Description = "Получение поста по RSS for GooglePlus")]
        [TestMethod]
        public void GetOnePostGPlus()
        {
            var lj = new GooglePlus();
            BlogPost bp = lj.GetOnePost("https://plus.google.com/111931627441418090108/posts/9YLnHfmDXZE?_utm_source=199-1-1");
            Assert.AreEqual(bp.Existance, true);
        }

        //[Test(Description = "Пост в виде чекина")]
        [TestMethod]
        public void GetCheckin()
        {
            Foursquare fsq = new Foursquare();
            BlogPost bp = fsq.GetOnePost("https://www.swarmapp.com/c/711dq0UDLpB");
            Assert.AreEqual(bp.Existance, true);
        }

        //[Test(Description = "Твит в виде чекина")]
        [TestMethod]
        public void GetTwitterCheckin()
        {
            var twt = new Twitter();
            twt.LogInto(new UserAccount("f1ashr", "qwe00qwe"));
            BlogPost bp = twt.GetOnePost("https://twitter.com/mini_for_money_/status/744233236327342080");
        }

        //[Test(Description = "Твит в виде чекина")]
        [TestMethod]
        public void GetBlogspot()   
        {
            var bs = new Blogspot();
            BlogPost bp = bs.GetOnePost("http://seoded.blogspot.com/2016/08/blog-post.html");
            Assert.AreEqual(bp.Existance, true);
        }

        //[Test(Description = "Image Preview Loading")]
        [TestMethod]
        public void LoadImagePreview()
        {
            //ImageServer imager = (ImageServer)BlogsAPI.Common.GetImagerByLink("http://giphy.com/gifs/fandor-mAxdv7OJWzq6Y?sdasda");
            BlogsAPI.Images.Instagram imager = new BlogsAPI.Images.Instagram();
            //Assert.AreNotEqual(imager.GetThumb("http://lockerz.com/s/203739811"), null);
            //Assert.AreNotEqual(imager.GetThumb("https://www.instagram.com/p/BBxky8ehNxdm5iE1Pu-LX4_H8GQ2NPb4Fc1cfc0/"), null);
            Assert.AreNotEqual(imager.GetThumb("https://www.instagram.com/p/BDWSbyhCpby/"), null);
            //Assert.AreNotEqual(imager.GetThumb("http://giphy.com/gifs/fandor-mAxdv7OJWzq6Y?sdasda"), null);
        }

        //251291024289427602_143845251
        //[Test(Description = "Instagr.am Media Loading")]
        [TestMethod]
        public async void LoadInstagramMedia()
        {
            InstaSharp.Endpoints.Media client = new InstaSharp.Endpoints.Media(Instagram.APIKey);
            client.EnableEnforceSignedHeader("127.0.0.1");
            var media = await client.Get("334561794796274331_5179079");
            //var client = new Unauthenticated(Instagram.APIKey);
            //MediaResponse media = client.Get("334561794796274331_5179079");
            Debug.WriteLine(media.Data.CreatedTime.ToLocalTime());
            Assert.IsTrue(media.Data.Comments.Nodes.Count > 0);
        }

        //251291024289427602_143845251
        //[Test(Description = "Instagr.am Media Loading")]
        [TestMethod]
        public async void LoadInstagramComments()
        {
            InstaSharp.Endpoints.Comments client = new InstaSharp.Endpoints.Comments(Instagram.APIKey);
            client.EnableEnforceSignedHeader("127.0.0.1");
            //InstaSharp.Endpoints.Comments.Unauthenticated client = new InstaSharp.Endpoints.Comments.Unauthenticated(Instagram.APIKey);
            CommentsResponse comments = await client.Get("251291024289427602_143845251");
            Assert.IsTrue(comments.Data.Count > 0);
        }

        [TestMethod]
        public void GooglePlusPerson()
        {
            GooglePlus gp = new GooglePlus();
            var user = gp.GetUser("111778712650735272804");
            Assert.IsNotNull(user);
        }

        [TestMethod]
        public void GooglePlusSearch()
        {
            GooglePlus gp = new GooglePlus();
            var user = gp.Search("AliakseiSherakov");
            Assert.IsNotNull(user);
        }

        [TestMethod]
        public void DetectImageFaceApi()
        {
            FaceApi fa = new FaceApi("6b2401f749be496da8244a2a805f4be0");
            var json = fa.ProcessImage("https://prod-thumbnail.pscp.tv/jz8dgj2CAse7VU3NikT1zxERYGM2HUJumsD0RzQrSyZnZMZblfjcQhqtX8FhPQc1mH-v6UqFFCCehjO-nOrJXA/chunk_840.jpg?Expires=1806447920&Signature=CYz9Cfibm1cSNcilVUA32Ocp0U9ZK9nHFCwhj9K74PhxGnAIignYmQOLbfGLaGmWADTNj1VBem5udzzXXNJn90F5L-kL-WgbgmzHYqiNgpaC~x2KE9r29yZ2D97kldWJaPP6k-s9AP5zXV8bdTmAuIxyvMjYoDfaapz4tnObH7cRLRb2AHxp9WtQghfbo-J0Ri~aihl4KmDFG9A3XxZBYzY0Q1hK1BTNm6ha8SSbSkLqduVHeTsordGtCgzw9-7iVom4fTMTAeFFbjJ~lVOxvR~bA~sG7ShgUQPLIfI0teFEFp4ISUU-imtGl-C03qmdQvCMT9TvZK1jwBt2bKJmzA__&Key-Pair-Id=APKAIHCXHHQVRTVSFRWQ",
                FaceFields.age | FaceFields.gender);
            Assert.IsTrue(json.Status == HttpStatusCode.OK);
            Assert.IsNotNull(json.JsonData);
        }
    }
}
